//
//  SimScaleFlowView.m
//  Knowbox
//
//  Created by LiuXubin on 14/12/30.
//  Copyright (c) 2014年 knowin. All rights reserved.
//

#import "SimScaleFlowView.h"
#import "UIView+SimAdditions.h"

@interface FlowScrollView : UIScrollView

@end

@implementation FlowScrollView

- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
    return [view isKindOfClass:[UIButton class]];
}

@end

@interface SimScaleFlowView ()
{
    BOOL   _innerEndScroll;
}

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, assign) CGSize baseViewSize;
@property (nonatomic, assign) CGSize maxViewSize;
@property (nonatomic, assign) NSInteger viewCount;
@property (nonatomic, assign) NSInteger visibleCount;
@property (nonatomic, strong) NSMutableDictionary *viewDict;

@end


@implementation SimScaleFlowView


- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _currentIndex = NSNotFound;
        _offScreenX = 50;
        self.clipsToBounds = YES;
    }
    return self;
}

- (void)refreshLayoutView
{
    for (int i = 0; i < _viewCount; i++) {
        UIView *view = _viewDict[@(i)];
        CGPoint viewCenter = CGPointMake((i+0.5)*_maxViewSize.width, self.height/2);
        CGPoint convertCenter = [_scrollView convertPoint:viewCenter toView:self];
        
        if (convertCenter.x - _maxViewSize.width/2 + _offScreenX<= 0 ||
            convertCenter.x + _maxViewSize.width/2 - _offScreenX>= self.width) {
            if (view) {
                [UIView animateWithDuration:0.2
                                 animations:^{
                    view.alpha = 0.0f;
                }
                 completion:^(BOOL finished) {
                     [view removeFromSuperview];
                     [_viewDict removeObjectForKey:@(i)];
                 }];
            }
        }
        else{
            if (!view) {
                view = [_dataSource flowView:self viewAtIndex:i];
                _viewDict[@(i)] = view;
                view.tag = kPageViewBaseTag + i;
                [_scrollView insertSubview:view atIndex:0];

                view.alpha = 0.0f;
                [UIView animateWithDuration:0.2
                                 animations:^{
                                     view.alpha = 1.0f;
                                 }
                                 completion:^(BOOL finished) {
//                                     [view removeFromSuperview];
//                                     [_viewDict removeObjectForKey:@(i)];
                                 }];
                
                UIView *separatorLine = nil;
                if ([_dataSource respondsToSelector:@selector(flowView:separateLineAtIndex:)]) {
                    separatorLine = [_dataSource flowView:self separateLineAtIndex:i];
                    separatorLine.center = CGPointMake(i * _maxViewSize.width, self.height/2);
                    [_scrollView insertSubview:separatorLine atIndex:1];
                }
            }
            
            if (convertCenter.x <= self.width/2-_maxViewSize.width/2 ||
                convertCenter.x >= self.width/2+_maxViewSize.width/2) {
                view.transform = CGAffineTransformScale(CGAffineTransformIdentity, _minViewScale, _minViewScale);
            }
            else{
                CGFloat offX = fabs(convertCenter.x - self.width/2);
                CGFloat scale = 1.0 + (_maxViewScale-1.0) * (1 - offX/_maxViewSize.width);
                view.transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale);
            }
            
            view.center = viewCenter;
        }
    }
}

- (NSArray *)allVisibleViews
{
    return [_viewDict allValues];
}

- (void)reloadData
{
    [_scrollView removeAllSubviews];
    if (_viewDict) {
        [_viewDict removeAllObjects];
    }
    else{
        _viewDict = [NSMutableDictionary dictionary];
    }
    
    if (!_scrollView) {
        _scrollView = [[FlowScrollView alloc] initWithFrame:self.bounds];
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.clipsToBounds = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.delaysContentTouches = NO;
        _scrollView.canCancelContentTouches = YES;
        [self insertSubview:_scrollView atIndex:0];
    }

    _baseViewSize = [_dataSource sizeForFlowView:self];
    _viewCount = [_dataSource numberOfPagesInFlowView:self];
    _maxViewSize = CGSizeMake(floor(_baseViewSize.width*_maxViewScale+_viewGap), floor(_baseViewSize.height*_maxViewScale+_viewGap));
    _scrollView.width = _maxViewSize.width;
    _scrollView.center = CGPointMake(self.width/2, self.height/2);
    _scrollView.contentSize = CGSizeMake(_maxViewSize.width*_viewCount, self.height);
    _scrollView.contentOffset = CGPointZero;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if ([view isEqual:self]) {
        for (UIView *subview in _scrollView.subviews) {
            CGPoint offset = CGPointMake(point.x - _scrollView.left + _scrollView.contentOffset.x - subview.left, point.y - _scrollView.top + _scrollView.contentOffset.y - subview.top);
            if ((view = [subview hitTest:offset withEvent:event])){
                return view;
            }
        }
        
        return _scrollView;
    }
    
    return view;
}

- (UIView *)viewForPage:(NSInteger)index
{
    return _viewDict[@(index)];
}

- (void)scrollToPage:(NSUInteger)pageNumber animated:(BOOL)animated
{
    _innerEndScroll = NO;
    self.userInteractionEnabled = YES;
    
    CGFloat offset = floor(pageNumber*_maxViewSize.width);
    if (_scrollView.contentOffset.x == offset) {
        [self scrollViewEndScroll:_scrollView];
    }
    else{
        self.userInteractionEnabled = NO;
        //修复系统setContentOffset, animate为NO 调用scrollViewDidEndScrollingAnimation的Bug
        _innerEndScroll = animated ? NO : YES;
        [_scrollView setContentOffset:CGPointMake(offset, 0) animated:animated];
        _innerEndScroll = NO;
        if (!animated) {
            [self scrollViewEndScroll:_scrollView];
        }
    }
}

- (void)scrollViewEndScroll:(UIScrollView *)scrollView
{
    NSInteger pageIndex = nearbyintf(scrollView.contentOffset.x / _maxViewSize.width);
    
    BOOL pageChanged = (_currentIndex != pageIndex);
    if (pageChanged) {
        if (_currentIndex != NSNotFound) {
            if ([_delegate respondsToSelector:@selector(flowView:willDisppearPage:)]) {
                [_delegate flowView:self willDisppearPage:_currentIndex];
            }
        }
        
        _currentIndex = pageIndex;
        [self refreshLayoutView];
        if ([_delegate respondsToSelector:@selector(flowView:didShowPage:)]) {
            [_delegate flowView:self didShowPage:_currentIndex];
        }
    }
    else{
        [self refreshLayoutView];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self refreshLayoutView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if (_innerEndScroll) {
        //系统自动触发sroll中断
        return;
    }
    
    [self scrollViewEndScroll:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self scrollViewEndScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate;
{
    if (!decelerate) {
        [self scrollViewEndScroll:scrollView];
    }
}

@end
